import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, removeToken } from '@/utils/auth'
import LangText from '@/framework/components/lang/LangText'
import SkuListEntity from '@/framework/components/sku/SkuListEntity'
import { EventBus } from '@/framework/infra/event/EventBus'
import EventNames from '@/infra/event/EventNames'
import { getAuth } from '@/framework/infra/auth/auth'
import { AppVersion } from '@/framework/constant/Common'

// const baseUrl = 'http://localhost:8080/api/v1'
const service = axios.create({
  timeout: 1000 * 60 * 5, // request timeout,,
  transformRequest: [function(data, headers) {
    // Do whatever you want to transform the data
    // Do whatever you want to transform the data
    if (typeof data === 'string' || data instanceof FormData) {
      return data
    }
    data = { ...data }
    Object.keys(data).forEach(key => {
      const value = data[key]
      if (value instanceof LangText) {
        Object.assign(data, value.getValue(data))
      } else if (value instanceof SkuListEntity) {
        Object.assign(data, value.getValue(key, data))
      }
    })
    return JSON.stringify(data)
  }],
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    config.headers['token'] = getToken()
    config.headers['AppVersion'] = AppVersion
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 500) {
        if (res.msg) {
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.reject(res)
      } else if (res.code === 2001 || res.code === 401) {
        if (!getAuth()) {
          return Promise.reject(res)
        }
        removeToken()
        EventBus.emit(EventNames.sessionOut)
        return Promise.reject(res)
      }
      return Promise.reject(res)
    } else {
      return res.data
    }
  },

  error => {
    if (error.msg) {
      Message({
        message: error.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
